/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ibmmodel3;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 *
 * @author mwh
 */
public class DistortionTableMem implements DistortionTable {

    final Map<DistortionKey, Double> table;

    /*
     * Apparently giza asigns same length to all target-sentences. Therefore we must use this instead of the
     * real length of the target sentence for lookups
     */
    int targetLength;


    public Iterator<DistortionKey> keyIterator() {
        return table.keySet().iterator();
    }


    public int getTargetLength() {
        return targetLength;
    }


    
    
    public DistortionTableMem(String filename) throws FileNotFoundException, IOException {
        table = new HashMap<DistortionKey, Double>();

        BufferedReader input = new BufferedReader(new FileReader(filename));
        String line;
        while ((line = input.readLine()) != null) {

            String[] tokens = line.split(" ");
            int os = targetLength;

            targetLength = Integer.parseInt(tokens[3]);
            if (os != targetLength) {
                System.err.println("NEQ" + os + " " + targetLength);
            }
            DistortionKey key = new DistortionKey(Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1]), Integer.parseInt(tokens[2]), Integer.parseInt(tokens[3]));
            Double value = Double.parseDouble(tokens[4]);

            table.put(key, value);
        }

    }


    public double get(DistortionKey k) {
        DistortionKey kk = new DistortionKey(k.SourcePos, k.TargetPos, k.SourceLength, targetLength);
      //  System.err.println(kk);
        if (table.containsKey(kk)) {
            return table.get(kk);
        }
        System.err.println("NO CONTAINING... ---------  ----------------------------");
        return Double.NaN;
    }


    public double getLog10(DistortionKey k) {
        return Math.log10(get(k));
    }
}
